#include <iostream>
#include <memory>
#include <string>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

std::string SuffixToType(const std::string &suffix)
{
  if (suffix == ".html")
    return "text/html";
  else if (suffix == ".jpg")
    return "image/jpeg";
  else if (suffix == ".jpg")
    return "image/png";
  else
  {
  }
  return "text/html";
}

std::string CodeToDsc(int code)
{
  switch (code)
  {
  case 200:
    return "OK";
    break;
  case 301:
    return "MOVED PERMANENTLY";
    break;
  case 307:
    return "TEMPORARY REDIRECT";
    break;
  case 403:
    return "FIRBIDDEN";
    break;
  case 505:
    return "SERVER ERROR";
    break;
  default:
    return "UNKNOWN";
  }
}

std::string HandlerHttpRequest(std::string &request)
{
  std::unique_ptr<Factory> factory(new Factory());
  auto req = factory->BuildRequest();

  // 反序列化
  req->DeSerialize(request);
  req->Parse();
  req->HttpDebug();

  int code = 200;

  std::string content = req->GetFileContent();
  if (content.empty())
  {
    code = 404;
    content = req->Get_404();
  }
  // std::cout<<content<<std::endl;

  auto resp=factory->BuildResPonse();
  resp->SetCode(code);
  resp->SetCodeDesc(CodeToDsc(code));
  resp->MakeStatusLine();
  std::string contentLength = "Content-Length: " + std::to_string(content.size()) + "\r\n";
  resp->AddHeader(contentLength);
  std::string contentType = "Content-Type: " + SuffixToType(req->GetSuffix()) + "\r\n";
  resp->AddHeader(contentType);
  resp->AddContent(content);

  std::string namecookie="Set-Cookie: username=zhangsan\r\n";
  resp->AddHeader(namecookie);
  std::string passwdcookie="Set-Cookie: passwd=12345\r\n";
  resp->AddHeader(passwdcookie);
  std::string statuscookie="Set-Cookie: status=login\r\n";
  resp->AddHeader(statuscookie);

  return resp->Serizlizer();
}

int main(int argc, char *argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage: " << argv[0] << "port" << std::endl;
    return 1;
  }
  uint16_t localport = std::stoi(argv[1]);
  std::unique_ptr<TcpServer> svr(new TcpServer(localport, HandlerHttpRequest));
  svr->Loop();
  return 0;
}
